

#include "ThreadManager.h"

#define LOG_TAG "ThreadManager"

enum MsgIDThread {
  MsgIDThread_Destroy = MsgID_None
};

ThreadManager *ThreadManager::_Instance = nullptr;

ThreadManager *ThreadManager::Instance() {
  if (_Instance == nullptr) {
    _Instance = new ThreadManager();
    _Instance->startThread();
  }

  return _Instance;
}

void ThreadManager::Destroy() {
  if (_Instance) {
    _Instance->stopThread();

    _Instance->waitFinish();

    DELETE_PTR(_Instance)
  }
}

bool ThreadManager::createThread(HandlerThread *pThread, void *param) {
  if (pThread && pThread->startThread()) {
    return pThread->sendMessage(Msg_Create(MsgID_Init, param));
  }
  return false;
}

void ThreadManager::destroyThread(HandlerThread *pThread) {
  if (pThread) {
    sendMessage(Msg_Create(MsgIDThread_Destroy, pThread));
  }
}

void ThreadManager::handleMessage(Message *pMsg) {
  if (pMsg && pMsg->what == MsgIDThread_Destroy) {
    if (pMsg->pObj) {
      auto pThread = static_cast<HandlerThread *>(pMsg->pObj);
      pThread->stopThread();

      pThread->waitFinish();

      LOG_INFO("destroy thread. %s", pThread->getClassName())
      DELETE_PTR(pThread)
    }
  }
}

const char *ThreadManager::getClassName() {
  return "ThreadManager";
}

void ThreadManager::toString() {
  LOG_TEST("ThreadManager tid:%d", Get_TID())
}